package com.jieli.bt.att.ui.settings.log

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jieli.bt.att.data.result.OpResult
import com.jieli.bt.att.util.FileUtil
import com.jieli.logcat.JL_Log
import java.io.File

/**
 * @author zqjasonZhong
 * @since 2024/11/6
 * @email zhongzhuocheng@zh-jieli.com
 * @desc 打印文件逻辑实现
 */
class LogFileViewModel : ViewModel() {

    companion object {

        const val OP_DELETE_FILE = 0x20

        const val OP_DELETE_FOLDER = 0x21
    }

    val tag = LogFileViewModel::class.simpleName

    val logFilesMLD = MutableLiveData<MutableList<File>>()
    val opResMLD = MutableLiveData<OpResult<Boolean>>()

    val logFileDirPath = JL_Log.getLogOption().logFileOption.logFileDirPath


    fun readLogFiles() {
        val folder = File(logFileDirPath)
        if (!folder.exists()) return
        folder.listFiles()?.filter {
            it.isFile && it.length() >= 1024
                    && (it.name.endsWith(".txt") || it.name.endsWith(".TXT"))
        }.also { list ->
            val files = list?.toMutableList() ?: mutableListOf()
            files.sortByDescending { it.lastModified() }
            logFilesMLD.postValue(files)
        }
    }

    fun deleteFile(filePath: String) {
        if (FileUtil.deleteFile(File(filePath))) {
            readLogFiles()
            return
        }
        opResMLD.postValue(
            OpResult(
                OP_DELETE_FILE,
                message = "Failed to delete File.\n filePath : $filePath",
                data = false
            )
        )
    }

    fun clearLog() {
        if (FileUtil.deleteFile(File(logFileDirPath))) {
            logFilesMLD.postValue(mutableListOf())
            return
        }
        opResMLD.postValue(
            OpResult(
                OP_DELETE_FOLDER,
                message = "Failed to delete folder.\n filePath : $logFileDirPath",
                data = false
            )
        )
    }
}